package com.qst.medical.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qst.medical.domain.MedicalDrug;
import com.qst.medical.mapper.MedicalDrugMapper;
import com.qst.medical.model.MedicalDrugModel;
import com.qst.medical.model.MedicalDrugQC;
import com.qst.medical.model.SSDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @Author: xwg
 * @CreateDate: 2023/9/4
 */

@Service
public class MedicalDrugService {
    @Value("${spring.web.resources.static-locations}")
    private String staticLocation;
    @Autowired
    private MedicalDrugMapper medicalDrugMapper;

    public MedicalDrug insert(MedicalDrugModel medicalDrugModel) {
        MedicalDrug medicalDrug = new MedicalDrug();
        medicalDrug.setMdName(medicalDrugModel.getMdName());
        medicalDrug.setProducer(medicalDrugModel.getProducer());
//       code= 1692220225
        Integer code = (int) System.currentTimeMillis();
        medicalDrug.setMdId(code);
        medicalDrug.setUpdateTime(LocalDateTime.now());
        medicalDrug.setOperator(SecurityContextHolder.getContext().getAuthentication().getName());
//      db:  /1692220225.jpg
        String origin = medicalDrugModel.getPic().getOriginalFilename();
        String ext = origin.substring(origin.lastIndexOf("."));
        medicalDrug.setPicUrl("/" + code + ext);
        medicalDrugMapper.insert(medicalDrug);
        MultipartFile pic = medicalDrugModel.getPic();
        String replacedLocation = staticLocation.replace("file:", "");
//         pic.transferTo("D:/share/1692220225.jpg")
        try {
            pic.transferTo(Paths.get(replacedLocation,
                    code + ext));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(medicalDrug);
        return medicalDrug;
    }

    public PageInfo<MedicalDrug> query(MedicalDrugQC medicalDrugQC) {
        String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
        PageHelper.startPage(medicalDrugQC.getPageNum(), medicalDrugQC.getPageSize());
        List<MedicalDrug> results = medicalDrugMapper.dynamicQuery(medicalDrugQC, currentUser);
        return new PageInfo<>(results);
    }

    public List<SSDto> ss() {
        return medicalDrugMapper.ss();

    }
}
